﻿using OpenCvSharp;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Drawing;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Timers;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace VideoPlayer
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : System.Windows.Window
    {
        string rtmp = ConfigurationManager.AppSettings["videoStreamUrl"];

        /*
         * 视频流地址
         * 播放前动画
         */
        public bool IsStartPlay { get; private set; }
        VideoCapture videoCapture;
        VideoInfo videoInfo = null;       
        private object LockHelper = new object();
        Timer myTimer = new Timer();
    
       
        public MainWindow()
        {
            InitializeComponent();
            Border border = borderTitle;
            border.MouseMove += delegate (object sender, System.Windows.Input.MouseEventArgs e) {
                if (e.LeftButton == MouseButtonState.Pressed)
                {
                    this.DragMove();
                }
            };

            this.Top = 111;
            this.Left = 166;
            this.Loaded += MainWindow_Loaded;
            Log($"打开软件");
            myTimer.Elapsed += MyTimerElapsed;
        }

        private void MainWindow_Loaded(object sender, RoutedEventArgs e)
        {
            //OpenCvSharp.Mat src = new OpenCvSharp.Mat("lena.png", OpenCvSharp.ImreadModes.Color);
            //Cv2.ImShow("src", src);
            //Cv2.WaitKey(0);
           
            videoInfo = new VideoInfo();         
            Log($"videoStreamUrl rtmp :{rtmp}");
            Task.Run(PlayVideo);
        }
        private void refreshVideo_Click(object sender, RoutedEventArgs e)
        {          
            myTimer.Stop();
            VideoShow.Source = new BitmapImage(new Uri("pack://application:,,,/Image/loginImg.png"));       
            gifImage.Visibility = Visibility.Visible;
            Task.Run(PlayVideo);
        }

        private void PlayVideo()
        {
            videoCapture = new VideoCapture(rtmp);
            if (videoCapture.IsOpened())
            {
                this.Dispatcher.Invoke(() => { gifImage.Visibility = Visibility.Collapsed; });
                videoInfo.Filename = rtmp;
                videoInfo.Width = (int)videoCapture.FrameWidth;
                videoInfo.Height = (int)videoCapture.FrameHeight;
                videoInfo.Fps = (int)videoCapture.Fps;
               
                myTimer.Interval = videoInfo.Fps == 0 ? 300 : 1000 / videoInfo.Fps;
                IsStartPlay = true;
                myTimer.Start();
            }
            else
            {
                this.Dispatcher.Invoke(() => { gifImage.Visibility = Visibility.Collapsed; });
                Log($"视频源异常 rtmp :{rtmp}");
                MessageBox.Show("视频源异常");
            }
        }

        private void MyTimerElapsed(object sender, ElapsedEventArgs e)
        {
            if (IsStartPlay)
            {
                lock (LockHelper)
                {
                    var frame = videoCapture.RetrieveMat();
                    if (frame != null)
                    {
                        if (frame.Width == videoInfo.Width && frame.Height == videoInfo.Height)
                        {
                            this.SetVideoCapture(frame);
                            videoInfo.PlaySate = PlaySate.Playing;
                        }
                        else 
                        {
                            Log($"bad frame");
                        }                       
                    }
                }
            }
        }
        private void SetVideoCapture(Mat frame)
        {
            var bitImage = frame.Clone();         
            Application.Current?.Dispatcher.Invoke(() =>
            {
                var imageSource = BitmapSourceConvert.MatToBitmapImage(bitImage);
                this.VideoShow.Source = imageSource;
            });
        }
        private void closeButton_Click(object sender, RoutedEventArgs e)
        {
            Log($"关闭软件");
            this.Close();
        }

       
        private void Log(string contend)
        {
            string log = System.IO.Path.Combine(AppDomain.CurrentDomain.BaseDirectory, DateTime.Now.ToString("yyyyMMdd") + ".log");
            File.AppendAllText(log, $"{DateTime.Now} {contend}\r\n");          
        }

    }
}
